const mysql = require("mysql2/promise");
const bcrypt = require("bcrypt");
const config = require("../config/base");
const pool = require("../config/database");

class User {
  static async create({ username, password, nickname }) {
    let connection;
    try {
      // 创建数据库连接
      connection = await mysql.createConnection(config.db);

      // 加密密码
      const hashedPassword = await bcrypt.hash(password, 10);

      // 插入用户数据，添加 nickname 字段
      const [result] = await connection.execute(
        "INSERT INTO users (username, password, nickname) VALUES (?, ?, ?)",
        [username, hashedPassword, nickname || null]
      );

      return result;
    } finally {
      if (connection) {
        await connection.end();
      }
    }
  }

  static async findByUsername(username) {
    let connection;
    try {
      connection = await mysql.createConnection(config.db);
      const [rows] = await connection.execute(
        "SELECT * FROM users WHERE username = ?",
        [username]
      );
      return rows[0];
    } finally {
      if (connection) {
        await connection.end();
      }
    }
  }

  static async verifyPassword(inputPassword, hashedPassword) {
    return bcrypt.compare(inputPassword, hashedPassword);
  }

  static async updateUserInfo(userId, { nickname, phone, avatar }) {
    let connection;
    try {
      connection = await mysql.createConnection(config.db);

      // 构建动态 SQL 语句和参数
      const updates = [];
      const params = [];

      if (avatar !== undefined) {
        updates.push("avatar = ?");
        params.push(avatar);
      }
      if (nickname !== undefined) {
        updates.push("nickname = ?");
        params.push(nickname);
      }
      if (phone !== undefined) {
        updates.push("phone = ?");
        params.push(phone);
      }

      // 如果没有要更新的字段，直接返回
      if (updates.length === 0) {
        return true;
      }

      // 添加 userId 到参数数组
      params.push(userId);

      const sql = `UPDATE users SET ${updates.join(", ")} WHERE id = ?`;
      const [result] = await connection.execute(sql, params);

      if (result.affectedRows === 0) {
        throw new Error("用户不存在");
      }
      return true;
    } catch (error) {
      console.error("更新用户信息失败:", error);
      throw error;
    } finally {
      if (connection) {
        await connection.end();
      }
    }
  }
}

module.exports = User;
